package com.xiguthings.waka.web.controller.wechat.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiguthings.waka.publicUtils.PropertiesUtil;
import com.xiguthings.waka.web.controller.wechat.wx.beans.Msg;
import com.xiguthings.waka.web.controller.wechat.wx.beans.MsgType;
import com.xiguthings.waka.web.controller.wechat.wx.beans.msgbody.MpnewsBody;
import com.xiguthings.waka.web.controller.wechat.wx.beans.msgbody.TextBody;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.util.Arrays;

@Component
public class WxService {

    private static String TOKEN = "westv123";
    protected Logger log = Logger.getLogger(WxService.class);

    /**
     * 微信验证服务器的方法
     *
     * @return
     */
    public static String ConfigureServer(String signature, String timestamp, String nonce, String echostr) {
        Logger log = Logger.getLogger(WxService.class);
        log.info("开始验证微信token----------------------");
        log.info("signature:" + signature + ",echostr:" + echostr + ",timestamp:" + timestamp + ",nonce:" + nonce);
        String[] str = {TOKEN, timestamp, nonce};
        Arrays.sort(str); // 字典序排序
        String bigStr = str[0] + str[1] + str[2]; // SHA1加密
        String digest = SHA1(bigStr).toLowerCase();
        // 确认请求来至微信
        if (digest.equals(signature)) {
            log.info("验证微信token---,结果为：通过");
            // out.write(echostr.getBytes());
            // out.flush();
            return echostr;
        } else {
            log.info("验证微信token---,结果为：错误");
            return "error";
        }
    }

    /**
     * SHA1算法
     *
     * @param decrypt
     * @return
     */
    private static String SHA1(String decrypt) {
        // 获取信息摘要 - 参数字典排序后字符串
        try {
            // 指定sha1算法
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decrypt.getBytes());
            // 获取字节数组
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("签名错误！");
        }
    }

    /**
     * 消息处理入口
     *
     * @param jmsg
     * @return
     * @throws Exception
     */
    public String handle(JSONObject jmsg) throws Exception {
        if (jmsg.get("MsgType").equals(MsgType.EVENT)) {
            if (jmsg.containsKey("Event")) {// 进行事件类型判断
                // 进行点击后跳转页面事件操作
                if (((String) jmsg.get("Event")).toUpperCase().equals("CLICK")) {
                    return doEventClick(jmsg);
                }
                if (jmsg.get("Event").equals("subscribe")) {
                    // 用户关注，发送欢迎消息和绑定方法
                    return doEventSubscribe(jmsg);
                }
            }
        }
        return null;
    }

    /**
     * 新关注的粉丝，发送消息
     *
     * @param jmsg
     * @return
     */
    private String doEventSubscribe(JSONObject jmsg) {
//		String FromUserName = (String) jmsg.get("FromUserName");
//		Owner owner = ownerservice.findByOpenid(FromUserName);
//		if (owner == null) {
//			owner = new Owner();
//			owner.setOpenid(FromUserName);
//			ownerservice.saveOrUpdate(owner);
//		}
//		String hy = "";
//		try {
//			hy = new String(PropertiesUtil.getInstance().getPro("config/msg.properties", "hy").getBytes("ISO-8859-1"),
//					"UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
//		 WxUtil.sendTextMsg(FromUserName, hy);
        return "新的粉丝进入，已经发送（本服务器的日志）";
    }

    /**
     * 执行click按钮事件,并发送文本消息
     *
     * @param jmsg
     * @param
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    private String doEventClick(JSONObject jmsg)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        String eventKey = jmsg.get("EventKey").toString();
        Method method = this.getClass().getDeclaredMethod("do_" + eventKey, JSONObject.class);
        method.setAccessible(true);
        String msg = null;
        try {
            msg = (String) method.invoke(this, jmsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }

    private String do_button_1_1(JSONObject jmsg) {
        return null;

    }

    private String do_button_1_2(JSONObject jmsg) {
        return null;

    }

    private String do_button_1_3(JSONObject jmsg) {
        return null;

    }

    private String do_button_1_4(JSONObject jmsg) {
        return null;

    }

    private String do_button_1_5(JSONObject jmsg) {
        return null;

    }

    private String do_button_2_1(JSONObject jmsg) throws UnsupportedEncodingException {
        String FromUserName = jmsg.getString("FromUserName");
        Msg msg = new Msg();
        String mediaId = new String(PropertiesUtil.getInstance().getPro("config/msg.properties", "button_2_1_media_id")
                .getBytes("ISO-8859-1"), "UTF-8");
        intiMpnewsMsg(mediaId, msg, FromUserName);
        String msgStr = JSON.toJSONString(msg);
        WxConnExec.sendMsg(msgStr);
        return msgStr;
    }

    private String do_button_2_2(JSONObject jmsg) throws UnsupportedEncodingException {
        String FromUserName = jmsg.getString("FromUserName");
        Msg msg = new Msg();
        String mediaId = new String(PropertiesUtil.getInstance().getPro("config/msg.properties", "button_2_2_media_id")
                .getBytes("ISO-8859-1"), "UTF-8");
        intiMpnewsMsg(mediaId, msg, FromUserName);
        String msgStr = JSON.toJSONString(msg);
        WxConnExec.sendMsg(msgStr);
        return msgStr;
    }

    private String do_button_2_3(JSONObject jmsg) throws UnsupportedEncodingException {
        String FromUserName = jmsg.getString("FromUserName");
        Msg msg = new Msg();
        String mediaId = new String(PropertiesUtil.getInstance().getPro("config/msg.properties", "button_2_3_media_id")
                .getBytes("ISO-8859-1"), "UTF-8");
        intiMpnewsMsg(mediaId, msg, FromUserName);
        String msgStr = JSON.toJSONString(msg);
        WxConnExec.sendMsg(msgStr);
        return msgStr;
    }

    private String do_button_2_4(JSONObject jmsg) {
        return null;
    }

    private String do_button_2_5(JSONObject jmsg) {
        return null;
    }

    private String do_button_3_1(JSONObject jmsg) {
        return null;
    }

    private String do_button_3_2(JSONObject jmsg) {
        return null;
    }

    private String do_button_3_3(JSONObject jmsg) throws UnsupportedEncodingException {
        String FromUserName = jmsg.getString("FromUserName");
        Msg msg = new Msg();
        String mediaId = new String(PropertiesUtil.getInstance().getPro("config/msg.properties", "button_3_3_media_id")
                .getBytes("ISO-8859-1"), "UTF-8");
        intiMpnewsMsg(mediaId, msg, FromUserName);
        String msgStr = JSON.toJSONString(msg);
        WxConnExec.sendMsg(msgStr);
        return msgStr;
    }

    private String do_button_3_4(JSONObject jmsg) {
        return null;
    }

    private String do_button_3_5(JSONObject jmsg) {
        return null;
    }

    /**
     * 编辑文本信息的方法
     *
     * @param bodyStr
     * @param msg
     * @param FromUserName
     * @return
     */
    public Msg intiTextMsg(String bodyStr, Msg msg, String FromUserName) {
        if (msg == null) {
            msg = new Msg();
        }
        msg.setTouser(FromUserName);
        msg.setMsgtype(MsgType.TEXT);
        TextBody textBody = new TextBody();
        msg.setText(textBody);
        textBody.setContent(bodyStr);
        return msg;
    }

    /**
     * 编辑文本信息的方法
     *
     * @param bodyStr
     * @param msg
     * @return
     */
    public Msg intiTextMsg(String bodyStr, Msg msg) {
        if (msg == null || StringUtils.isEmpty(msg.getTouser())) {
            throw new RuntimeException("信息中没有指明发送的人");
        }
        TextBody textBody = new TextBody();
        msg.setText(textBody);
        textBody.setContent(bodyStr);
        return msg;
    }

    /**
     * 编辑图文（点击跳转到图文消息页面）消息
     *
     * @param mediaId
     * @param msg
     * @param FromUserName
     * @return
     */
    public Msg intiMpnewsMsg(String mediaId, Msg msg, String FromUserName) {
        if (msg == null) {
            msg = new Msg();
        }
        msg.setMsgtype(MsgType.MPNEWS);
        msg.setTouser(FromUserName);
        MpnewsBody mpnews = new MpnewsBody();
        mpnews.setMedia_id(mediaId);
        msg.setMpnews(mpnews);
        return msg;
        // {
        // "touser":"OPENID",
        // "msgtype":"mpnews",
        // "mpnews":
        // {
        // "media_id":"MEDIA_ID"
        // }
        // }
    }

}
